package org.aksw.xoperator.command;

import java.util.regex.Pattern;

import org.aksw.xoperator.sparql.SparqlEndpointFacade;
import org.aksw.xoperator.sparql.SparqlEndpointIdentifier;
import org.aksw.xoperator.sparql.SparqlQuery;
import org.aksw.xoperator.transform.ITransformSparqlToText;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

public class QueryCommand extends Command{
	
	private Log log  = LogFactory.getLog(QueryCommand.class);
	
	private SparqlEndpointFacade endpoints;
	
	private ITransformSparqlToText transform;

	@Override
	public String getHelp() {
		
		return "Queries all rdf stores";
	}

	@Override
	public String getKeyWord() {
		return "query";
	}

	@Override
	public Pattern getValidationPattern() {
		// TODO Auto-generated method stub
		return Pattern.compile(".*");
	}

	@Override
	public void performInternal(Chat chat, Message message) {
		SparqlQuery query = new SparqlQuery(message.getBody().substring(6));


		endpoints.process(query);
		
		for (SparqlEndpointIdentifier ident : query.getResults().keySet()) {
			if(query.getResults().get(ident).getErrorMsg()==null||query.getResults().get(ident).getErrorMsg().isEmpty()){
				try {
					chat.sendMessage("RDF-Store " + ident.getName() + " (" +ident.getType()+ ") " + "answered:"  + transform.transformXML(query.getResults().get(ident).getAnswer()));
				} catch (XMPPException e) {
					log.error(e);
				}
			}
			
		}
		
		
	}

	public QueryCommand(SparqlEndpointFacade endpoints,
			ITransformSparqlToText transform) {
		super();
		this.endpoints = endpoints;
		this.transform = transform;
	}



}
